package com.rongxue.service.utils;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.rongxue.pojo.SProject;
import com.rongxue.pojo.SUser;
import com.rongxue.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class PDFHelper {
	private static Logger LOG = LoggerFactory.getLogger(PDFHelper.class);

	public static  Map<String, String> map = new HashMap<>();

	public static String inUrl = FxqUtils.jksSavePath+"/model.pdf";
	public static String outUrl= FxqUtils.jksSavePath+"/template.pdf";

//	public static String inUrl = "/www/wwwroot/pay.shmengzhiya.com/pdf/template.pdf";//模板pdf路径
//	public static String outUrl= "/www/wwwroot/pay.shmengzhiya.com/pdf/template2.pdf";//生成未盖章pdf路径

//	public static String prefixFont = "C:/WINDOWS/Fonts/SIMSUN.TTC,1";//winodws系统中文字体
	public static String prefixFont ="/usr/share/fonts/chinese/msyh.ttf";//linux系中文统字体



	/***
	 * PDF文件转PNG图片，全部页数
	 *
	 * @param PdfFilePath
	 * @param dstImgFolder
	 * @param dpi
	 * @return
	 */
//	public static String pdf2Image(String PdfFilePath, String dstImgFolder, int dpi) {
//		File file = new File(PdfFilePath);
//		PDDocument pdDocument;
//		try {
//			String imgPDFPath = file.getParent();
//			int dot = file.getName().lastIndexOf('.');
//			String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
//			String imgFolderPath = null;
//			if (dstImgFolder.equals("")) {
//				imgFolderPath = imgPDFPath + File.separator + imagePDFName;// 获取图片存放的文件夹路径
//			} else {
//				imgFolderPath = dstImgFolder + File.separator + imagePDFName;
//			}
//
//			if (FileHelper.createDirectory(imgFolderPath)) {
//				pdDocument = PDDocument.load(file);
//				PDFRenderer renderer = new PDFRenderer(pdDocument);
//				/* dpi越大转换后越清晰，相对转换速度越慢 */
//				int pages = pdDocument.getNumberOfPages();
//				StringBuffer imgFilePath = null;
//				for (int i = 0; i < pages; i++) {
//					String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName;
//					imgFilePath = new StringBuffer();
//					imgFilePath.append(imgFilePathPrefix);
//					imgFilePath.append("_");
//					imgFilePath.append(String.valueOf(i + 1));
//					imgFilePath.append(".png");
//					File dstFile = new File(imgFilePath.toString());
//					BufferedImage image = renderer.renderImageWithDPI(i, dpi);
//					ImageIO.write(image, "png", dstFile);
//				}
//				System.out.println("PDF文档转PNG图片成功！");
//				return dstImgFolder;
//
//			} else {
//				LOG.info("PDF文档转PNG图片失败：" + "创建" + imgFolderPath + "失败");
//				return null;
//			}
//
//		} catch (IOException e) {
//			LOG.info("PDF文档转PNG图片异常：" + e.getMessage());
//			e.printStackTrace();
//            return null;
//		}
//
//	}

	/**
	 * 将pdf域填上内容
	 */
	public static String PDFFill(SProject sProject, SUser sUser){
		Map<String, Object> map = new HashMap<>();
		OutputStream os = null;
		PdfStamper ps = null;
		PdfReader reader = null;

		try {
			// 1 读取pdf表单
			reader = new PdfReader(inUrl);
			// 2 输出pdf表单
			os = new FileOutputStream(outUrl);
			// 3 根据表单生成一个新的pdf
			ps = new PdfStamper(reader, os);
			// 4 获取pdf表单
			AcroFields form = ps.getAcroFields();
			// 5给表单添加中文字体 这里采用系统字体。不设置的话，中文可能无法显示
			BaseFont bf = BaseFont.createFont(prefixFont,
					BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			form.addSubstitutionFont(bf);
			// 6查询数据================================================


//			String count = map.get("count");
//			if (count==null || "".equals(count)) count="001";


			String regNo = "HT"+ DateUtil.formatLongDateTime();


            Map<String, Object> data = new HashMap<String, Object>();
			data.put("regNo", regNo);
			data.put("financing",sUser.getRealName());
			data.put("idcard", sUser.getCardNo());
			data.put("userName", sProject.getRealName());
            data.put("mobile", sProject.getUsername());
            data.put("amount",sProject.getDue_capital());
			data.put("addTime", sProject.getAddTime().substring(0,10));
//			data.put("investDirectionTitle", sProject.getInvestDirectionTitle()==null? "":sProject.getInvestDirectionTitle());
			data.put("investDirectionTitle", "经营周转");
			data.put("startTime", DateUtil.formatDate(sProject.getFrozenDate()));
			data.put("endTime", DateUtil.formatDate(sProject.getEndTime()));
			data.put("repaymentType", "一次性到期还本付息");
			data.put("bigAmount", NumberUtil.getNumberStr(sProject.getDue_capital().intValue()));
			data.put("duration", sProject.getDuration());
			data.put("userInterest",sProject.getUser_interest()+"%");

			LOG.info("map-------"+data.toString());

			// 7遍历data 给pdf表单表格赋值
			for (String key : data.keySet()) {
				form.setField(key,data.get(key).toString());
			}
			ps.setFormFlattening(true);

			//-----------------------------pdf 添加图片----------------------------------
			// 通过域名获取所在页和坐标，左下角为起点
//            System.out.println("pdf 添加图片");
			// String imgpath="E:/sign/pdf2/ddddd.pdf";
//            int pageNo = form.getFieldPositions("img").get(0).page;
//            Rectangle signRect = form.getFieldPositions("img").get(0).position;
//            float x = signRect.getLeft();
//            float y = signRect.getBottom();
//            // 读图片
//            Image image = Image.getInstance(imgpath);
//            // 获取操作的页面
//            PdfContentByte under = ps.getOverContent(pageNo);
//            // 根据域的大小缩放图片
//            image.scaleToFit(signRect.getWidth(), signRect.getHeight());
//            // 添加图片
//            image.setAbsolutePosition(x, y);
//            under.addImage(image);
			//-------------------------------------------------------------
			LOG.info("===============PDF导出成功=============");
			return regNo;
		} catch (Exception e) {
			LOG.info("===============PDF导出失败=============");
			e.printStackTrace();
			return null;
		} finally {
			try {
				ps.close();
				reader.close();
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
